package com.addplus.townmall.server.scheduled.scheduletask;

import com.addplus.townmall.server.api.mapper.town.ShopProductFightMapper;
import com.addplus.townmall.server.api.mapper.town.ShopProductMapper;
import com.addplus.townmall.server.api.mapper.town.ShopSpecificationSkuMapper;
import com.addplus.townmall.server.api.model.town.ShopProduct;
import com.addplus.townmall.server.api.model.town.ShopProductFight;
import com.addplus.townmall.server.api.model.town.ShopSkuModel;
import com.addplus.townmall.server.api.model.town.ShopSpecificationSku;
import com.addplus.townmall.server.api.mongodao.ShopSkuModelDao;
import com.addplus.townmall.server.api.utils.date.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.mongodb.morphia.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class SkuTask {

    private Logger logger = LoggerFactory.getLogger(UpdateCommentTask.class);

    @Autowired
    private ShopSkuModelDao shopSkuModelDao;

    @Autowired
    private ShopSpecificationSkuMapper shopSpecificationSkuMapper;

    /**
     * 定时：1个小时
     * 同步更新mango的商品sku信息
     */
    @Scheduled(cron = "0 0 0/1 * * ? ")
    public void updateMangoShopProductSku() {
        // 获取商品sku列表
        List<ShopSpecificationSku> skuList = shopSpecificationSkuMapper.selectList(new QueryWrapper<ShopSpecificationSku>()
                .eq("is_deleted", 0));
        logger.info("-----------------开始执行更新mango（商品sku）操作----------------- ");
        // mangoDB 插入商品sku
        List<ShopSkuModel> shopSkuModels = new ArrayList<>();
        skuList.stream().forEach(o -> {
            // 根据shopProductId 和 type 删除原有mongo数据
            Query<ShopSkuModel> skuQuery = shopSkuModelDao.createQuery(ShopSkuModel.class);
            skuQuery.field("shopProductId").equal(o.getShopProductId());
            skuQuery.field("type").equal(o.getType());
            shopSkuModelDao.deleteByQuery(skuQuery);
            ShopSkuModel shopSkuModel = new ShopSkuModel();
            BeanUtils.copyProperties(o, shopSkuModel);
            shopSkuModel.setShopSpecificationSkuId(o.getId());
            shopSkuModel.setId(null);
            shopSkuModels.add(shopSkuModel);
        });
        shopSkuModelDao.insert("ShopSkuModel", shopSkuModels);
        logger.info("-----------------更新mango（商品sku）操作结束----------------- ");
    }

}
